<template>
  <view class="food-container">
    <!-- 顶部标题栏 -->
    <view class="header-section">
      <view class="search-wrapper">
        <view class="search-input-container">
          <u-icon name="search" size="18" color="#999" class="search-icon"></u-icon>
          <input class="search-input" v-model="searchKeyword" placeholder="搜索美食..." @confirm="onSearch"
            @input="onSearchInput" :confirm-type="'search'" />
          <view v-if="searchKeyword" class="clear-btn" @tap="clearSearch">
            <u-icon name="close-circle-fill" size="18" color="#999"></u-icon>
          </view>
        </view>
      </view>
    </view>

    <!-- 美食列表 -->
    <scroll-view class="content-scroll" scroll-y @scrolltolower="loadMore" refresher-enabled
      :refresher-triggered="refreshing" @refresherrefresh="onRefresh">
      <!-- 加载状态 -->
      <view v-if="loading && worksList.length === 0" class="loading-wrapper">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 空状态 -->
      <view v-else-if="!loading && worksList.length === 0" class="empty-wrapper">
        <text class="empty-icon">🍽️</text>
        <text class="empty-text">暂无美食分享</text>
        <text class="empty-desc">快来分享你的美食吧~</text>
      </view>

      <!-- 美食列表 -->
      <view v-else class="works-list">
        <view class="work-item card rounded-xl" v-for="work in worksList" :key="work.id" @tap="onWorkTap(work)">
          <!-- 图片区域 -->
          <view v-if="work.mediaType === 'image' && work.imagesUrls && work.imagesUrls.length > 0"
            class="work-image-wrapper">
            <image class="work-image" :src="work.imagesUrls[0]" mode="aspectFill" :lazy-load="true"></image>
            <!-- 多图标识 -->
            <view v-if="work.imagesUrls.length > 1" class="image-count-badge">
              <text class="image-count-text">{{ work.imagesUrls.length }}</text>
            </view>
          </view>

          <!-- 视频封面 -->
          <view v-else-if="work.mediaType === 'video' && work.videoCover" class="work-image-wrapper">
            <image class="work-image" :src="work.videoCover" mode="aspectFill" :lazy-load="true"></image>
            <view class="video-play-icon">
              <text class="play-icon">▶</text>
            </view>
          </view>

          <!-- 内容区域 -->
          <view class="work-content">
            <view style="display: flex; gap: 12rpx;">
              <!-- 标题 -->
              <view class="work-header">
                <text class="work-title">{{ work.title }}</text>
              </view>

              <!-- 标签 -->
              <view v-if="work.tags && work.tags.length > 0" class="work-tags">
                <text class="tag-item" v-for="(tag, index) in work.tags.slice(0, 3)" :key="index">
                  #{{ tag }}
                </text>
              </view>
            </view>

            <!-- 底部信息 -->
            <view class="work-footer">
              <view class="author-info">
                <image v-if="work.author?.avatar" class="author-avatar" :src="work.author.avatar" mode="aspectFill">
                </image>
                <image v-else class="author-avatar" src="/static/logo.png" mode="aspectFill"></image>
                <text class="author-name">{{ work.author?.username || '匿名用户' }}</text>
              </view>

              <view class="work-stats">
                <view class="stat-item">
                  <!-- 方法1: 使用 uView Plus 图标组件（推荐） -->
                  <u-icon name="eye" color="#999" size="24"></u-icon>
                  <!-- 方法2: 使用 CSS 绘制的图标 -->
                  <!-- <view class="stat-icon stat-icon-eye"></view> -->
                  <!-- 方法3: 使用 Unicode 字符 -->
                  <!-- <text class="stat-icon">👁️</text> -->
                  <text class="stat-value">{{ work.viewsCount || 0 }}</text>
                </view>
                <view class="stat-item">
                  <u-icon name="heart" color="#ff6b6b" size="24"></u-icon>
                  <text class="stat-value">{{ work.likesCount || 0 }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 加载更多 -->
        <view v-if="hasMore && !loading" class="load-more-wrapper">
          <text class="load-more-text">上拉加载更多</text>
        </view>

        <view v-if="loading && worksList.length > 0" class="load-more-wrapper">
          <text class="load-more-text">加载中...</text>
        </view>

        <view v-if="!hasMore && worksList.length > 0" class="load-more-wrapper">
          <text class="load-more-text">没有更多了</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getFoodList, type WorkInfo, type WorksListResponse } from '@/api/works'

// 作品列表
const worksList = ref<WorkInfo[]>([])
// 分页信息
const currentPage = ref(1)
const pageSize = ref(10)
const totalPages = ref(0)
const hasMore = ref(true)
// 加载状态
const loading = ref(false)
const refreshing = ref(false)
// 搜索关键词
const searchKeyword = ref('')
// 搜索防抖定时器
let searchTimer: ReturnType<typeof setTimeout> | null = null

/**
 * 加载美食列表
 */
const loadWorksList = async (page: number = 1, isRefresh: boolean = false) => {
  if (loading.value) return

  try {
    loading.value = true

    const keyword = searchKeyword.value.trim() || undefined
    const response: WorksListResponse = await getFoodList(page, pageSize.value, keyword)

    if (isRefresh) {
      worksList.value = response.data
    } else {
      worksList.value = [...worksList.value, ...response.data]
    }

    currentPage.value = response.page
    totalPages.value = response.totalPages
    hasMore.value = response.page < response.totalPages

  } catch (error: any) {
    console.error('加载美食列表失败:', error)
    uni.showToast({
      title: error.message || '加载失败，请重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

/**
 * 搜索输入
 */
const onSearchInput = () => {
  // 清除之前的定时器
  if (searchTimer) {
    clearTimeout(searchTimer)
  }

  // 如果输入框为空，立即搜索（清空搜索）
  if (!searchKeyword.value.trim()) {
    performSearch()
    return
  }

  // 防抖：500ms 后执行搜索
  searchTimer = setTimeout(() => {
    performSearch()
  }, 500)
}

/**
 * 执行搜索
 */
const performSearch = () => {
  currentPage.value = 1
  hasMore.value = true
  loadWorksList(1, true)
}

/**
 * 搜索确认
 */
const onSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  performSearch()
}

/**
 * 清空搜索
 */
const clearSearch = () => {
  searchKeyword.value = ''
  performSearch()
}

/**
 * 下拉刷新
 */
const onRefresh = () => {
  refreshing.value = true
  currentPage.value = 1
  hasMore.value = true
  loadWorksList(1, true)
}

/**
 * 加载更多
 */
const loadMore = () => {
  if (!hasMore.value || loading.value) return
  loadWorksList(currentPage.value + 1, false)
}

/**
 * 点击作品
 */
const onWorkTap = (work: WorkInfo) => {
  uni.navigateTo({
    url: `/pages/detail/detail?id=${work.id}`
  })
}

// 页面加载时获取数据
onMounted(() => {
  loadWorksList(1, true)
})
</script>

<style scoped>
.food-container {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

/* 顶部标题栏 */
.header-section {
  background-color: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

/* 搜索栏 */
.search-wrapper {
  width: 100%;
}

.search-input-container {
  position: relative;
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 50rpx;
  padding: 0 24rpx;
  height: 72rpx;
}

.search-icon {
  flex-shrink: 0;
  margin-right: 16rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  height: 100%;
}

.search-input::placeholder {
  color: #999;
}

.clear-btn {
  flex-shrink: 0;
  margin-left: 12rpx;
  padding: 4rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-title {
  font-size: 44rpx;
  font-weight: bold;
  color: #000;
  letter-spacing: 2rpx;
}

.page-subtitle {
  font-size: 26rpx;
  color: #999;
}

/* 内容滚动区 */
.content-scroll {
  flex: 1;
  overflow-y: auto;
}

/* 加载状态 */
.loading-wrapper {
  padding: 100rpx 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

/* 空状态 */
.empty-wrapper {
  padding: 150rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20rpx;
}

.empty-icon {
  font-size: 120rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 32rpx;
  color: #666;
  font-weight: 500;
}

.empty-desc {
  font-size: 26rpx;
  color: #999;
}

/* 作品列表 */
.works-list {
  padding: 20rpx 30rpx;
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

/* 作品卡片 */
.work-item {
  background-color: #fff;
  overflow: hidden;
  /* Material Design 阴影 */
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.08),
    0 4rpx 8rpx rgba(0, 0, 0, 0.06),
    0 8rpx 16rpx rgba(0, 0, 0, 0.04);
  transition: box-shadow 0.3s, transform 0.3s;
}

.work-item:active {
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.12),
    0 8rpx 16rpx rgba(0, 0, 0, 0.08),
    0 16rpx 32rpx rgba(0, 0, 0, 0.06);
  transform: translateY(-2rpx);
}

/* 图片区域 */
.work-image-wrapper {
  width: 100%;
  height: 400rpx;
  position: relative;
  overflow: hidden;
}

.work-image {
  width: 100%;
  height: 100%;
}

/* 多图标识 */
.image-count-badge {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  background: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(10rpx);
  border-radius: 20rpx;
  padding: 8rpx 16rpx;
}

.image-count-text {
  font-size: 24rpx;
  color: #fff;
  font-weight: 500;
}

/* 视频播放图标 */
.video-play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100rpx;
  height: 100rpx;
  background: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(10rpx);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.play-icon {
  font-size: 40rpx;
  color: #fff;
  margin-left: 6rpx;
}

/* 内容区域 */
.work-content {
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.work-header {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.work-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #000;
  flex: 1;
}


/* 标签 */
.work-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
}

.tag-item {
  font-size: 24rpx;
  color: #4A90E2;
  background: #E5F3FF;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

/* 底部信息 */
.work-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.author-avatar {
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  background-color: #f0f0f0;
}

.author-name {
  font-size: 24rpx;
  color: #666;
}

.work-stats {
  display: flex;
  gap: 24rpx;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.stat-icon {
  font-size: 24rpx;
}

.stat-value {
  font-size: 24rpx;
  color: #999;
}

/* 加载更多 */
.load-more-wrapper {
  padding: 40rpx 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.load-more-text {
  font-size: 26rpx;
  color: #999;
}
</style>
